<?php

namespace app\api\controller;


use app\admin\model\BillModel;
use app\admin\model\BuildingRoomBoardModel;
use app\admin\model\BuildingRoomFixedModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomPtModel;
use app\admin\model\BuildingZoneModel;
use app\admin\model\HouseModel;
use app\admin\model\HouseOwnerModel;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;


class Building extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @var BuildingModel
     */
    protected $model = null;

    protected $user_id = 0;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new BuildingModel();
        $this->user_id = $this->auth->id;
    }

    public function index()
    {
        $id = $this->request->param('id/d', 0);
        $page_size = $this->request->param('page_size/d', 15);
        $zone_id = $this->request->param('zone_id/d');
        $keyword = $this->request->param('keyword/s', '');
        $where = [];
        if ($id) {
            $where['id'] = $id;
        }
        if ($keyword) {
            $where['name|address'] = ['like', '%' . $keyword . '%'];
        }
        if ($zone_id) {
            $where['zone_id'] = $zone_id;
        }

        $real_name = HouseOwnerModel::where('user_id', $this->user_id)->value('real_name', '');
        $list = $this->model
            ->with(['rooms' => function ($query) {
                $query->field('id,name,floor_no,type,status,build_id,zone_id,create_time,update_time');
            }])
            ->where($where)
            ->whereIn('id', $this->model::getUserBuildingIds($this->user_id))
            ->order('id', 'desc')
            ->paginate($page_size)->each(function ($item, $key) use ($real_name) {
                $item['real_name'] = $real_name;
            });
        file_put_contents('bsql.txt',$this->model->getLastSql());
        $list = $list->toArray();
        if ($list['total'] > 0) {

            foreach ($list['data'] as $k => $v) {
                // 已签约
                $list['data'][$k]['signed'] = BuildingRoomModel::where([
                    'build_id' => $v['id'],
                    'status' => 3,
                ])->count();
                // 待签约
                $list['data'][$k]['wait_sign'] = BuildingRoomModel::where([
                    'build_id' => $v['id'],
                    'status' => ['neq', 3],
                ])->count();


                $list['data'][$k]['zone'] = BuildingZoneModel::where('id', $v['zone_id'])->value('name','');

                if (!empty($v['rooms'])) {
                    foreach ($v['rooms'] as $kk => $item) {
                        $house_status = HouseModel::where('room_id', $item['id'])->order('id', 'desc')->value('status', 0);
                        $list['data'][$k]['rooms'][$kk]['house_status'] = $house_status;
                    }
                }

            }
            file_put_contents('bsqlssss.txt',json_encode($list,true));
        }

        $this->success('请求成功', $list);
    }


    public function address_list()
    {
        $kw = $this->request->param('kw/s', '');
        $zone_id = $this->request->param('zone_id/d', 0);
        $page = $this->request->param('page/d', 1);
        $page_size = $this->request->param('page_size/d', 15);
        $where = [];
        if ($kw) {
            $where['name|address'] = ['like', '%' . $kw . '%'];
        }
        if ($zone_id) {
            $where['zone_id'] = $zone_id;
        }
        $list = $this->model->where($where)
            ->where("find_in_set($this->user_id,user_id)")
            ->order('id', 'desc')
            ->field('id,name,address,zone_id')
            ->page($page,$page_size)
            ->select();

        foreach ($list as $item) {
            $item->append([], true);
        }


        $this->success('请求成功', $list);
    }

    public function stat()
    {
        $id = $this->request->param('id/d', 0);
        $zone = $this->request->param('zone_id/d', $this->request->param('zone/d'));
        $keyword = $this->request->param('keyword/s', '');
        $where = [];

        $ids = BuildingModel::getUserBuildingIds($this->user_id);
        if ($id) {
            $ids = array_intersect($ids, [$id]);
        }

        $where['id'] = ['in', $ids];
        if ($keyword) {
            $where['address'] = ['like', '%' . $keyword . '%'];
        }
        if ($zone) {
            $where['zone_id'] = $zone;
        }
        $building_ids = $this->model
            ->where($where)
            ->column('id');

        $roomModel = new BuildingRoomModel();
        $rented = $roomModel->whereIn('build_id', $building_ids)
            ->where('status', 3)->count();

        $not_rented = $roomModel->whereIn('build_id', $building_ids)
            ->where('status', 'neq',3)->count();

        $publish = $roomModel->whereIn('build_id', $building_ids)
            ->whereIn('status', [1, 2])->count();

        $total = $roomModel->whereIn('build_id', $building_ids)->count();
        $rate = ($total > 0 ? round($rented / $total * 100, 2) : 0) . '%';

        $data = compact('rented', 'not_rented', 'publish', 'rate');
        $this->success('请求成功', $data);
    }


    public function stat_list()
    {
        $id = $this->request->param('id/d', 0);
        $flag = $this->request->param('flag/d', 0);
        $page_size = $this->request->param('page_size/d', 10);
        $zone = $this->request->param('zone_id/d', $this->request->param('zone/d'));
        $keyword = $this->request->param('kw/s', '');

        if (!in_array($flag, [1, 2, 3])) {
            $this->error('flag错误');
        }

        $where = [];
        $ids = BuildingModel::getUserBuildingIds($this->user_id);
        if ($id) {
            $ids = array_intersect($ids, [$id]);
        }

        $where['id'] = ['in', $ids];
        if ($keyword) {
            $where['address'] = ['like', '%' . $keyword . '%'];
        }
        if ($zone) {
            $where['zone_id'] = $zone;
        }
        $building_ids = $this->model
            ->where($where)
            ->column('id');

        $diy_where = [
            'build_id' => ['in', $building_ids],
        ];
        if ($flag == 1) {
            $diy_where['status'] = 3;
        } elseif ($flag == 2) {
            $diy_where['status'] = ['in', [1, 2]];
        } else {
            $diy_where['status'] = ['neq', 3];
        }

        $roomModel = new BuildingRoomModel();
        $field = 'id,name,type,build_id,house_type,floor_no,price,area';
        $list = $roomModel
            ->with(['building' => function ($query) {
                $query->removeOption('soft_delete')->withField('id,address');
            }])
            ->where($diy_where)
            ->field($field)
            ->paginate($page_size)->each(function ($item) {
                $item->append(['type_text'], true);
            });

        $this->success('请求成功', $list);
    }

    public function option_list()
    {
        //$data = $this->model->where("find_in_set($this->user_id,user_id)")->column('distinct zone');
        //$data = BuildingZoneModel::where('user_id', $this->user_id)->column('id,name');
        $data = BuildingZoneModel::where("find_in_set($this->user_id,user_id)")->column('id,name');
        $this->success('success', $data);
    }

    public function add()
    {
        $this->checkIsHouseOwner();
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'name|楼栋名称' => 'require',
            'address|楼栋地址' => 'require',
            'floor_num|楼层数' => 'require|integer',
            'area|面积' => 'require|number',
            'images|图片' => 'length:0,6',
            'zone_id|楼栋区域' => 'require',
        ], [
            'images.length' => '图片最多上传6张'
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $params['user_id'] = $this->auth->id;
        $create = $this->model->create($params, [
            'user_id', 'name', 'address', 'floor_num', 'area', 'images', 'zone_id'
        ]);

        if ($create->id) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }


    public function del()
    {
        $ids = $this->request->param('ids');

        $list = $this->model->where('id', 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $item->data('del_uid', $this->auth->id);
                $count += $item->delete();

                // 删除房间
                $room_list = BuildingRoomModel::where([
                    'build_id' => $item['id']
                ])->select();
                foreach ($room_list as $r)  {
                    $r->data('del_uid', $this->auth->id);
                    $r->delete();
                }
                // 删除房源
                HouseModel::destroy([
                    'room_id' => array_column((array)$room_list, 'id'),
                ]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error('删除失败');
    }

    public function set_status()
    {
        $status = $this->request->param('status/d', 0);
        $room_id = $this->request->param('room_id/d', 0);
        if (!in_array($status, [2, 3])) {
            $this->error('状态错误');
        }
        if ($room_id <= 0) {
            $this->error('room_id错误');
        }

        Db::startTrans();
        try {
            $room = BuildingRoomModel::get($room_id);
            if (empty($room)) throw new Exception('房间不存在');
            $building_ids = BuildingModel::getUserBuildingIds($this->user_id);
            if(!in_array($room['build_id'], $building_ids)){
                throw new Exception('无权修改');
            }

            // 已签约改为待签约
            if ($room->status == 3 && $status == 2) {
                //throw new Exception('已签约完成，不可修改');

                $contract = \app\common\model\Contract::where('room_id', $room_id)
                    ->where('status', 1)
                    ->order('id', 'desc')->find();

                if($contract) {
                    BillModel::destroy([
                        'contract_id' => $contract->id,
                        'status' => ['in', [0, 1]],
                        'type' => 1,
                    ]);

                    BillModel::destroy([
                        'contract_id' => $contract->id,
                        'type' => 2,
                    ]);

                    // 合同更新为到期
                    $contract->status = 2;
                    $contract->remark .= '，房东更新房间状态为待签约，合同自动到期';
                    $contract->remark = trim($contract->remark, '，');
                    $contract->save();


                    // 重置房间状态
                    $status = 0;
                }
            }
            $room->save(['status' => $status]);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('修改成功');
    }

    /**
     * 下架
     * @return void
     */
    public function down()
    {
        $room_id = $this->request->param('room_id/d', 0);
        if ($room_id <= 0) {
            $this->error('room_id错误');
        }

        $house = HouseModel::order('id','desc')->where([
            'room_id' => $room_id
        ])->find();
        if (!$house) {
            $this->error('房源未发布请前去发布');
        }
        $room = BuildingRoomModel::get($room_id);
        $building_ids = BuildingModel::getUserBuildingIds($this->user_id);
        if(!in_array($room['build_id'], $building_ids)){
            $this->error('无权修改');
        }
        if ($house->status == -1) {
            $this->error('房源待审核，不可操作');
        }
        $res = $house->save(['status' => 2]);
        if ($res) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }


    /**
     * 上架
     * @return void
     */
    public function up()
    {
        $room_id = $this->request->param('room_id/d', 0);
        if ($room_id <= 0) {
            $this->error('room_id错误');
        }

        $house = HouseModel::order('id','desc')->where([
            'room_id' => $room_id
        ])->find();
        if (!$house) {
            $this->error('房源未发布请前去发布');
        }
        $room = BuildingRoomModel::get($room_id);
        $building_ids = BuildingModel::getUserBuildingIds($this->user_id);
        if(!in_array($room['build_id'], $building_ids)){
            $this->error('无权修改');
        }
        if ($house->status == -1) {
            $this->error('房源待审核，不可上架');
        }
        if ($house->is_finish == 1) {
            $this->error('房源已签约，不可操作');
        }
        if ($house->status == 1) {
            $res = true;
        } else {
            $res = $house->save(['status' => 1]);
        }

        if ($res) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 发布房源
     * @return void
     */
    public function publish()
    {
        $this->checkIsHouseOwner();
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'room_id|房屋id' => 'require|integer',
            'type|房屋类型' => 'require|in:1,2,3',
//            'community|社区' => 'require|integer',
//            'street|街道' => 'require|integer',
            'facilities|房屋设施' => 'require',
            'address|楼栋地址' => 'require',
            'floor|楼层' => 'require|integer',
            'area|面积' => 'require|number',
            'images|图片' => 'length:0,6',
        ], [
            'images.length' => '图片最多上传6张'
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $user_id = $this->auth->id;
        $params['user_id'] = $user_id;

        $publish_type = \app\common\model\User::isCanPublish($user_id);
        if ($publish_type == 0) {
            $this->error('次数已用完，积分不足');
        }

        Db::startTrans();
        try {
            $room_info = (new BuildingRoomModel())->get(['id' => $params['room_id']]);
            if (!$room_info) {
                throw new Exception('房间不存在');
            }
            $count = HouseModel::where('room_id', $params['room_id'])
                ->where('is_finish', 0)
                ->count();
            if ($count > 0) {
                throw new Exception('房源已经发布过了');
            }
            /*$is_audit = \app\common\model\User::where('id',$user_id)->value('is_audit');
            if ($is_audit == 0) {
                $params['status'] = 1;
            }*/
            $params['status'] = 1;
            HouseModel::create($params, true);
            $room_info->save(['status' => 1]);
            \app\common\model\User::decPublishNum($user_id, $publish_type);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('发布房源失败：'.$e->getTraceAsString());
            $this->error($e->getMessage());
        }

        $this->success('发布成功');
    }


    public function house()
    {
        $room_id = $this->request->param('room_id/d');
        if ($room_id <= 0) {
            $this->error('参数错误');
        }

        $data = HouseModel::where('room_id', $room_id)
            ->order('id', 'desc')
            ->field('delete_time,is_finish,comment_score', true)
            ->find();
        $this->success('成功', $data);
    }


    /**
     * 修改房源
     * @return void
     */
    public function house_modify()
    {
        $this->checkIsHouseOwner();
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'room_id|房屋id' => 'require|integer',
            'type|房屋类型' => 'require|integer',
            //'name|名称' => 'require',
//            'community|社区' => 'require|integer',
//            'street|街道' => 'require|integer',
            //'facilities|房屋设施' => 'require',
            'address|楼栋地址' => 'require',
            'region|片区' => 'require',
            'floor|楼层' => 'require|integer',
            'area|面积' => 'require|number',
            'images|图片' => 'length:0,6',
        ], [
            'images.length' => '图片最多上传6张'
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        if (empty($params['name']) && !empty($params['title'])) {
            $params['name'] = $params['title'];
        }

        unset($params['id']);
        unset($params['delete_time']);
        $user_id = $this->auth->id;
        Db::startTrans();
        try {
            $room_id = $params['room_id'];
            $room_info = (new BuildingRoomModel())->get(['id' => $room_id]);
            if (!$room_info) {
                throw new Exception('房间不存在');
            }
            $house = HouseModel::where('room_id', $room_id)
                ->order('id','desc')
                ->find();
            if (!$house) {
                throw new Exception('房源不存在');
            }
            $building_ids = BuildingModel::getUserBuildingIds($this->user_id);
            if(!in_array($room_info['build_id'], $building_ids)){
                throw new Exception('无权修改');
            }
            if ($house->is_finish == 1) {
                throw new Exception('房源已签约，不可修改');
            }
            /*$params['status'] = -1;
            $is_audit = \app\common\model\User::where('id',$user_id)->value('is_audit');
            if ($is_audit == 0) {
                $params['status'] = 1;
            }*/
            $params['status'] = 1;
            $house->allowField(true)->save($params);


            $force = true;
            BuildingRoomBoardModel::destroy(['room_id' => $room_id], $force);
            if (!empty($params['board'])) {
                array_walk($params['board'], function (&$item, $key, $room_id) {
                    unset($item['id']);
                    $item['room_id'] = $room_id;
                }, $room_id);

                (new BuildingRoomBoardModel())->allowField(true)->saveAll($params['board']);
            }
            BuildingRoomFixedModel::destroy(['room_id' => $room_id], $force);
            if (!empty($params['fixed'])) {
                array_walk($params['fixed'], function (&$item, $key, $room_id) {
                    unset($item['id']);
                    $item['room_id'] = $room_id;
                }, $room_id);
                (new BuildingRoomFixedModel())->allowField(true)->saveAll($params['fixed']);
            }
            BuildingRoomPtModel::destroy(['room_id' => $room_id], $force);
            if (!empty($params['pt'])) {
                array_walk($params['pt'], function (&$item, $key, $room_id) {
                    unset($item['id']);
                    $item['room_id'] = $room_id;
                }, $room_id);
                (new BuildingRoomPtModel())->allowField(true)->saveAll($params['pt']);
            }

            // 更新水电费用
            BuildingRoomModel::syncHouseData($room_id, $house);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('修改房源失败：'.$e->getTraceAsString());
            $this->error($e->getMessage());
        }

        $this->success('修改成功');
    }
}
